/*
 @Name: page插件
 @Author: ray
 @License: MIT
 */
; rayui.define(function (exports, undef) {
    "use strict";

    var $ = rayui.$,
        plugName = "page",
        globalIndex = 1000,
        dataCache = {},
        DealClass = function (options) {
            options.index = globalIndex;
            this.options = dataCache[globalIndex] = $.extend({}, DealClass.option, options);

            //初始化
            DealClass.utils.init.call(this);
            DealClass.utils.addEvents.call(this);
            return this;
        };

    DealClass.option = {
        align: 'left',//对齐方式，可选left|right | center，默认left
        groups: 5,//显示连续页码数量
        limit: 10, //每页显示的条数
        limits: [10, 20, 30, 40, 50, 60, 70, 80, 90],//分页条数选项
        curr: 1,//当前页
        count: 0,//总条数
        color: "",//选中颜色
        btnGroup: true,//按钮是否成组
        layout: [
            "count",//总条数
            "limit",//每页条数
            "first",//首页
            "pre",//上一页
            "page",//页码
            "next",//下一页
            "last",//最后一页
            "refresh",//刷新
            "jump"//跳转
        ],//布局

        //国际化支持
        btnFirstHtml: '<i class="ra ra-first"></i>',
        btnPreHtml: '<i class="ra ra-single-angle-left"></i>',
        btnNextHtml: '<i class="ra ra-single-angle-right"></i>', 
        btnLastHtml: '<i class="ra ra-last"></i>',
        btnRefreshHtml: '<i class="ra ra-refresh-s"></i>',
        limitText: "条/页",
        countLeftText: "共 ",
        countRightText: " 条",
        jumpLeftText: "到第",
        jumpRightText: "页",
        jumpBtnText: "确定"
    };

    DealClass.utils = {
        init: function () {
            var that = this,
                options = that.options;

            options.pages = Math.ceil(options.count / options.limit);
            //分页limit是否在limits里
            if (options.limits.indexOf(options.limit) === -1) {
                options.limits.push(options.limit);
                options.limits.sort(function (a, b) { return a - b; });
            }

            var $main = options.$main = $('<div class="rayui-page-boxmain"/>').appendTo($(options.elem)),
                curr = options.curr, isAdd,
                $btngps = options.$btngps = $('<div class="rayui-page-pagination"/>'),
                addBtnGps = function () {
                    if (!isAdd) {
                        isAdd = true;
                        $main.append($btngps);
                        DealClass.utils.initGroupBtns.call(that);
                    }
                };

            for (var i = 0, len = options.layout.length; i < len; i++) {

                switch (options.layout[i]) {
                    case "count":
                        $main.append('<span class="rayui-page-count">' + options.countLeftText + options.count + options.countRightText + '</span>');
                        break;//总条数
                    case "limit":
                        $main.append(function () {
                            var html = [];
                            html.push('<select class="rayui-page-limits">');
                            $(options.limits).each(function (a, b) {
                                html.push('<option value="' + b + '" ' + (options.limit === b ? "selected" : "") + '>' + b + ' ' + options.limitText + '</option>');
                            });
                            html.push('</select>');
                            return html.join('');
                        }());
                        break;//每页条数
                    case "first"://首页
                    case "pre"://上一页
                    case "next"://下一页
                    case "last"://最后一页
                    case "page"://页码
                        addBtnGps();
                        break;
                    case "refresh":
                        $main.append('<a class="rayui-btn btn-text page-item page-refresh" value="refresh">' + options.btnRefreshHtml + '</a>');
                        break;//刷新
                    case "jump":
                        $main.append('<span>' + options.jumpLeftText + '</span>');
                        $main.append('<input type="text" class="rayui-input rayui-page-input" min="1" value="' + curr + '"/>');
                        $main.append('<span>' + options.jumpRightText + '</span>');
                        $main.append('&nbsp;&nbsp;');
                        $main.append('<a class="rayui-btn rayui-page-btnok">' + options.jumpBtnText + '</a>');
                        break;//跳转
                }//end switch
            }//end for
            //自定义颜色
            options.btnGroup && $btngps.addClass('page-item-group');
            if (options.color) {
                var cssName = 'rayui-page-custom-' + options.index,
                    css = [
                        '<style>',
                        '.' + cssName + ' > a.page-active{',
                        'background-color: ' + options.color+';',
                        'border-color: ' + options.color,
                        '}',
                        '</style>'
                    ].join('');
                $main.append(css);
                $btngps.addClass(cssName);
            }
        },
        initGroupBtns: function () {
            var that = this,
                options = that.options,
                curr = options.curr,
                count = options.count,
                pages = options.pages,
                $btngps = options.$btngps;

            $btngps.html('');

            for (var i = 0, len = options.layout.length; i < len; i++) {

                switch (options.layout[i]) {
                    case "first":
                        $btngps.append('<a class="page-item page-first' + (curr === 1 || count === 0 ? " btn-disabled" : "") + '" value="first">' + options.btnFirstHtml + '</a>');
                        break;//首页
                    case "pre":
                        $btngps.append('<a class="page-item page-prev' + (curr === 1 || count === 0 ? " btn-disabled" : "") + '" value="pre">' + options.btnPreHtml + '</a>');
                        break;//上一页
                    case "page":
                        $btngps.append(function () {
                            var groups = pages < options.groups ? pages : options.groups,
                                halve = Math.floor((groups - 1) / 2),
                                end = Math.max(groups, (curr + halve) > pages ? pages : (curr + halve)),
                                start = (end - groups) < 1 ? 1 : end - groups + 1,
                                strTmp = [];

                            //分3部分加载
                            //part1
                            if (start > 1)
                                strTmp.push('<a class="page-item" value="1">1</a>');

                            //左分隔符
                            if (start > 2)
                                strTmp.push('<span class="page-omit">...</span>');

                            //part2
                            while (start <= end) {
                                strTmp.push('<a class="page-item" value="' + start + '">' + (start++) + '</a>');
                            }
                            //part3
                            //右分隔符
                            if (end < pages - 1)
                                strTmp.push('<span class="page-omit">...</span>');
                            if (end < pages)
                                strTmp.push('<a class="page-item" value="' + pages + '">' + pages + '</a>');

                            return strTmp.join('');
                        }());
                        break;//页码
                    case "next":
                        $btngps.append('<a class="page-item page-next' + (curr === pages || count === 0 ? " btn-disabled" : "") + '" value="next">' + options.btnNextHtml + '</a>');
                        break;//下一页
                    case "last":
                        $btngps.append('<a class="page-item page-last' + (curr === pages || count === 0 ? " btn-disabled" : "") + '" value="last">' + options.btnLastHtml + '</a>');
                        break;//最后一页
                }//end switch
            }//end for
            //选中
            $btngps.find(">a[value=" + curr + "]").addClass("page-active");
        },
        modify: function (tocurr, count) {
            var that = this,
                options = that.options,
                isModifyCurr = typeof tocurr === "number",
                isModifyCount = typeof count === "number";

            isModifyCurr && (options.curr = tocurr);
            isModifyCount && (options.count = count);

            if (options) {
                if (options.curr > options.pages) options.curr = options.pages;
                if (options.curr <= 0) options.curr = 1;
            }

            DealClass.utils.initGroupBtns.call(that);
            isModifyCount && options.$main.find('.rayui-page-count').html(options.countLeftText + options.count + options.countRightText);
        },
        addEvents: function () {
            var that = this,
                options = that.options,
                $main = options.$main;

            //page分页select
            $main.on("change." + plugName, "select.rayui-page-limits", function () {
                var preLimit = options.limit;
                options.limit = parseInt($(this).val());
                //按照数据重新计算pages
                options.pages = Math.ceil(options.count / options.limit);
                DealClass.utils.modify.call(that);
                //回调
                options.onPageLimitChanged && options.onPageLimitChanged(preLimit, options.limit);
            });

            //page页码
            $main.on("click.pageli." + plugName, ".page-item:not('.btn-disabled')", function () {
                var ss = $(this).attr("value"),
                    prePage = options.curr,
                    curr = options.curr;

                switch (ss) {
                    case "first": curr = 1; break;
                    case "pre": curr -= 1; break;
                    case "next": curr += 1; break;
                    case "last": curr = options.pages; break;
                    case "refresh": break;
                    default: curr = parseInt(ss); break;
                }

                DealClass.utils.modify.call(that, curr);
                //回调
                options.onPageJump && options.onPageJump(prePage, curr);
            });

            //input页码输入框
            $main.on("keyup." + plugName, ".rayui-page-input", function (e) {
                var value = this.value
                    , keyCode = e.keyCode;
                if (/^(37|38|39|40)$/.test(keyCode)) return;
                if (/\D/.test(value)) {
                    this.value = value.replace(/\D/, '');
                }
                var w = value.length * 10;
                //修改宽度
                $(this).width(10 + w);
                if (keyCode === 13) $main.find("a.rayui-page-btnok").click();
            });

            //page输入页码跳转
            $main.on("click.pagebtn." + plugName, "a.rayui-page-btnok", function () {
                var $input = $main.find(".rayui-page-input"),
                    input = $input.val(),
                    value = parseInt(input),
                    prePage = options.curr;
                if (input === '' || value < 1) return;

                DealClass.utils.modify.call(that, value);
                $input.val(options.curr);
                //回调
                options.onPageJump && options.onPageJump(prePage, value);
            });

        },
        on: function (event, func) {
            if (typeof event !== "string" || typeof func !== "function") return;
            var that = this,
                options = that.options;

            switch (event) {
                //页面跳转
                case "jump": options.onPageJump = func; break;
                //每页条数更改
                case "limitChanged": options.onPageLimitChanged = func; break;
            }
        }
    }

    DealClass.prototype = {
        on: function (event, callback) {
            DealClass.utils.on.call(this, event, callback);
            return this;
        },
        jump: function (tocurr) {
            this.modify(tocurr);
        },
        modify: function (tocurr, count) {
            DealClass.utils.modify.call(this, tocurr, count);
        }
    }

    var pagepg = {
        options: DealClass.option,
        render: function (options) {
            var classObj = new DealClass(options);
            dataCache[globalIndex++] = classObj;
            return classObj;
        }
    };

    exports(plugName, pagepg);
}, rayui.jsAsync());
